#wd = '/home/jc165798/Climate/CIAS/Australia/5km/bioclim_asc/'; setwd(wd) #define and set the raw data directory
wd = '/home/jc165798/Climate/CIAS/Australia/1km/bioclim_asc/'; setwd(wd)
od = '/home/jc148322/clim.data/Australia_1km/'; dir.create(od) #define and create the output directory


tfiles = list.files() #get a list of the files
tt = strsplit(tfiles,'_') #string split the file names
ESs = GCMs = NULL #set all to null
for (tval in tt) { ESs = c(ESs,tval[1]); GCMs = c(GCMs,tval[2]); } #extract all possible values
ESs = unique(ESs); GCMs = na.omit(unique(GCMs)) #keep only unique

script.dir='/home/jc148322/scripts/data_tasks/' #dir to write sh scripts to
setwd(script.dir)

###write out the combination of gcm & es
for (es in ESs) {
for (gcm in GCMs) {
	
	##create the sh file
	 zz = file(paste(es,'.',gcm,'.zip.sh',sep=''),'w')
		 cat('#!/bin/bash\n',file=zz)
		 cat('cd $PBS_O_WORKDIR\n',file=zz)
		 cat("R CMD BATCH --no-save --no-restore '--args gcm=\"",gcm,"\" es=\"",es,"\" ' ~/scripts/data_tasks/gcm.zip.r ",es,'.',gcm,'.Rout \n',sep='',file=zz) #run the R script in the background
	close(zz) 

	##submit the script
	system(paste('qsub -m n ',es,'.',gcm,'.zip.sh',sep=''))
}
}
ESs=ESs[3:length(ESs)]
###write out each emission scenario
for (es in ESs){ cat(es, '\n')
	
	##create the sh file
	 zz = file(paste(es,'.zip.sh',sep=''),'w')
		 cat('#!/bin/bash\n',file=zz)
		 cat('cd $PBS_O_WORKDIR\n',file=zz)
		 cat("R CMD BATCH --no-save --no-restore '--args es=\"",es,"\" ' ~/scripts/data_tasks/es.zip.r ",es,'.Rout \n',sep='',file=zz) #run the R script in the background
	close(zz) 

	##submit the script
	system(paste('qsub -m n ',es,'.zip.sh',sep=''))
}



###write out each GCM
for (gcm in GCMs) {

	##create the sh file
	 zz = file(paste(gcm,'.zip.sh',sep=''),'w')
		 cat('#!/bin/bash\n',file=zz)
		 cat('cd $PBS_O_WORKDIR\n',file=zz)
		 cat("R CMD BATCH --no-save --no-restore '--args gcm=\"",gcm,"\" ' ~/scripts/data_tasks/rcp_sres.zip.r ",gcm,'.Rout \n',sep='',file=zz) #run the R script in the background
	close(zz) 

	##submit the script
	system(paste('qsub -m n ',gcm,'.zip.sh',sep=''))
}



###write out the current
# zip(paste(od,'current.zip',sep=''),current,flags = "-r0X")

# current = ESs[grep('current',ESs)] #get the current asciis
# ESs = ESs[-grep('current',ESs)] #remove current from ESs


